"""
这个代码实现的是从草图到二维图像，调用通义万象模型
输入为提示词和前端上传的图片路径
输出为生成的图片的路径
"""
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
from datetime import datetime

def TongYi(prompt, sketch_image_url):
    # 获取当前时间并格式化为时间戳
    current_time = datetime.now()
    timestamp = current_time.strftime('%m%d-%H%M')

    # 确保输出目录存在
    output_directory = r'D:\Output'
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    print('----sync call, please wait a moment----')
    rsp = ImageSynthesis.call(api_key="sk-ec65775d12b84078adb05443392f1a95",
                              model="wanx-sketch-to-image-lite",
                              prompt=prompt,
                              n=1,
                              style='<3d cartoon>',
                              size='768*768',
                              sketch_image_url=sketch_image_url,
                              task="image2image")

    print('response: %s' % rsp)
    if rsp.status_code == HTTPStatus.OK:
        # 保存至目录
        for result in rsp.output.results:
            # 解析URL，提取文件名
            url_file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
            name, ext = os.path.splitext(url_file_name)  # 分离文件名和后缀

            # 创建文件名及路径
            file_name = f"{timestamp}{ext}"  # 创建新的文件名，包含时间戳和原始后缀
            file_path = os.path.join(output_directory, file_name)
            with open(file_path, 'wb+') as f:
                f.write(requests.get(result.url).content)
            print("文件已保存至:", file_path)
            return file_path  # 返回文件路径
    else:
        print('sync_call Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))
        return None  # 如果调用失败，返回None

# 示例调用
prompt = "一只多边形风格白色小猫，眼睛很大"
sketch_image_url = "D:/下载/lc-sp-hidream-1715758997714/data/1.png"
output_file_path = TongYi(prompt, sketch_image_url)